package com.origin.niuke.dynamic;

import java.util.Arrays;

/**
 * NC225 三角形最小路径和
 * 算法：动态规划
 *
 * @author yezh
 * @date 2022/11/30 21:15
 */
public class NC225 {

    public static void main(String[] args) {
        new NC225().minTrace(new int[][]{{2}, {3, 4}, {6, 5, 7}, {4, 1, 8, 3}});
    }

    public int minTrace(int[][] triangle) {
        // write code here
        int ans = Integer.MAX_VALUE, n = triangle.length, idx = 1, flag = 1;
        int[][] dp = new int[2][n];
        dp[0][0] = triangle[0][0];
        for (int i = 1; i < n; i++) {
            for (int j = 0; j <= i; j++) {
                if (j == 0) dp[idx][j] = dp[idx - flag][j];
                else if (j == i) dp[idx][j] = dp[idx - flag][j - 1];
                else dp[idx][j] = Math.min(dp[idx - flag][j], dp[idx - flag][j - 1]);
                dp[idx][j] += triangle[i][j];
            }
            idx = idx == 1 ? 0 : 1;
            flag = flag == 1 ? -1 : 1;
        }
        System.out.println(Arrays.deepToString(dp));
        for (int i = 0; i < n; i++) ans = Math.min(ans, dp[idx - flag][i]);
        return ans;
    }

}
